package com.gooseeker.mbus;

import java.util.Enumeration;
import java.util.List;

import org.apache.log4j.Logger;

import com.gooseeker.modbus.ConstValue;
import com.gooseeker.modbus.bean.SensorResultBean;
import com.gooseeker.modbus.bean.StationInfoBean;
import com.gooseeker.util.Constants;
/**
 * 数据检查线程，防止数据上报时候丢失或异常，导致的错误。
 * 初始化时候启动检查线程，检查DATA_MAP
 * 处理超过10S的数据入库
 * @author ysite
 *
 */
public class CheckDataThread implements Runnable {
	private Logger logger = Logger.getLogger(CheckDataThread.class);
	@Override
	public void run() {
		logger.debug("check datamap data to deal. size="+Constants.DATA_MAP.size());
		
		//循环2次
		int times = 0;
		while(times++ < 2)
		{
			List<SensorResultBean> tempBeanList  = null;
			Enumeration<StationInfoBean> en = Constants.DATA_MAP.keys();
			
			while(en.hasMoreElements())
			{
				StationInfoBean infoBean = en.nextElement();
				long duration = System.currentTimeMillis() - infoBean.getCreateTime();
				//超过10 秒数据删除一次
				if(duration >= 10 * 1000 )
				{
					tempBeanList = Constants.DATA_MAP.get(infoBean);
					
					logger.info("deal timeout data . tempBeanList="+tempBeanList.size());
					//保存数据到数据库
					SensorResultBean result = tempBeanList.get(0);
					short line1 = 0;
					short line2 = 0;
					for(int j = 0; j < tempBeanList.size(); j++)
					{
						line1 += tempBeanList.get(j).getValue1();
						line2 += tempBeanList.get(j).getValue2();
					}
					
					line1 = (short) (line1 / tempBeanList.size());
					line2 = (short) (line2 / tempBeanList.size());
					result.setValue1(line1);
					result.setValue2(line2);
					if (line1 < Constants.UNUSE_RESULT_DELTA && line2 < Constants.UNUSE_RESULT_DELTA)
					{
						result.setState(ConstValue.SENSOR_STATUS_UNUSE);
					}
					else if (line1 >= Constants.PASS_ADC_THRESHOLD_VALUE && line2 <= Constants.UNUSE_RESULT_DELTA)
					{
						result.setState(ConstValue.SENSOR_STATUS_PASS);
					}
					else
					{
						result.setState(ConstValue.SENSOR_STATUS_FAIL);
					}
					
					logger.debug("insert to DB for result ,infoBean="+infoBean.getAddress()+" , "+infoBean.getSubAddress());
					//入库
					Modbus.getInstance().insertToDB(infoBean, result);
					//删除MAP
					Constants.DATA_MAP.remove(infoBean);
					
					logger.debug("insert to DB finish ,infoBean="+infoBean.getAddress()+" , "+infoBean.getSubAddress()+" value="+result.getValue1()+"|"+result.getValue2());
				}
			}
			
			//10秒后执行第二次循环
			try 
			{
				Thread.sleep(20 * 1000);
			} catch (InterruptedException e) {
			}
		}
	}

}
